package com.atguigu.juc.homework3;

import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


class Ticket{
    Lock lock=new ReentrantLock();
    private int num =50;
    public void getTicket(){
        lock.lock();
        if (num > 0) {

            try {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "卖了第" + (num--) + "张票 ---还有" + num + "张票");
            } finally {
                lock.unlock();
            }
        }

        }
    }

public class MyThreadPoolDemo {
    public static void main(String[] args) {
        /**
         * 这个线程池长期创建有固定的线程数
         * newFixedThreadPool创建的线程池corePoolSize和maximumPoolSize值是相等的
         * ，它使用的是LinkedBlockingQueue
         */
        ExecutorService threadPool1 = Executors.newFixedThreadPool(5);
        /**
         *这个是一个线程池一个线程
         * newFixedThreadPool创建的线程池corePoolSize和maximumPoolSize值=1
         *          * ，它使用的是LinkedBlockingQueue<Runnable>()
         */
        ExecutorService threadPool2 = Executors.newSingleThreadExecutor();
        /**
         *newCachedThreadPool创建的线程池将corePoolSize设置为0，
         * 将maximumPoolSize设置为Integer.MAX_VALUE，它使用的是SynchronousQueue，
         * 也就是说来了任务就创建线程运行，当线程空闲超过60秒，就销毁线程。
         */
        ExecutorService threadPool3 = Executors.newCachedThreadPool();
        Ticket ticket=new Ticket();

        try {
            for (int i = 1; i <=3 ; i++) {
                //卖票程序
                threadPool3.submit(()->{
                    for (int j = 1; j <=50 ; j++) {
                        ticket.getTicket();
                    }

                });
            }
        } finally {
        threadPool3.shutdown();
        }

        //



    }
}
